<?php

namespace services\clinic;

use Yii;
use common\components\Service;
use common\models\clinic\UserTreatmentDetail;

/**
 * Class UserTreatmentDetailService
 * @package services\clinic
 */
class UserTreatmentDetailService extends Service
{
    /**
     * 根据ID查找信息
     *
     * @param int $id
     * @return UserTreatmentDetail|null
     */
    public function findById(int $id = 0): ?UserTreatmentDetail
    {
        return UserTreatmentDetail::find()->where(['id' => $id])->one();
    }

    /**
     * 查找信息
     *
     * @param array $condition
     * @return UserTreatmentDetail|null
     */
    public function findInfo(array $condition = []): ?UserTreatmentDetail
    {
        $query = UserTreatmentDetail::find();

        isset($condition['project_id']) && $query->andWhere(['project_id' => $condition['project_id']]);
        isset($condition['name']) && $query->andWhere(['name' => $condition['name']]);
        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);

        return $query->one();
    }

    /**
     * 查找列表
     *
     * @param array $condition
     * @return array|\yii\db\ActiveRecord[]
     */
    public function findList(array $condition = [])
    {
        $query = UserTreatmentDetail::find();

        isset($condition['select']) && $query->select($condition['select']);
        isset($condition['project_id']) && $query->andWhere(['project_id' => $condition['project_id']]);
        //isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);
        isset($condition['clinic_treatment_id']) && $query->andWhere(['clinic_treatment_id' => $condition['clinic_treatment_id']]);

        return $query->asArray()->all();
    }

    /**
     * 统计购买量【按治疗项目和诊室统计分组】
     *
     * @param array $params
     * @return array|\yii\db\ActiveRecord[]
     */
    public function statisticsByClinicProjectId(array $params = [])
    {
        // 购买量
        $query = UserTreatmentDetail::find()
            ->select(['clinic_project_id', 'section_name', 'GROUP_CONCAT(patient_card_id) AS patient_card_ids', 'SUM(num) as buy_number'])
            ->where(['project_id' => $params['project_id']])
            ->groupBy('clinic_project_id,section_name');

        if (isset($params['start_time']) && $params['start_time']) {
            $query->andWhere(['>=', 'created_at', strtotime($params['start_time'])]);
        }

        if (isset($params['end_time']) && $params['end_time']) {
            $query->andWhere(['<=', 'created_at', strtotime($params['end_time'].' 23:59:59')]);
        }

        return $query->asArray()->all();
    }
}
